package com.loong.user.handler;


import com.loong.common.utils.TransformUtils;
import com.loong.user.business.ManageResourceBusiness;
import com.loong.user.common.backend.param.ManageResourceParam;
import com.loong.user.common.backend.param.ManageResourceTreeParam;
import com.loong.user.common.backend.result.ManageResourceResult;
import com.loong.user.common.backend.result.ResourceGroupTreeResult;
import com.loong.user.model.ManageResource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: 后台系统资源服务
 * @Author: hzp
 * @Date: 2020-10-16 11:46
 */
@Component
public class ManageResourceHandler {
    @Resource
    private ManageResourceBusiness manageResourceBusiness;


    /**
     * 保存后台系统资源
     * @param param
     */
    public void save(ManageResourceParam param){
        manageResourceBusiness.save(TransformUtils.transform(param, ManageResource.class));
    }

    /**
     * 更新后台系统资源
     * @param param
     */
    public void update(ManageResourceParam param){
        manageResourceBusiness.updateByPrimaryKeySelective(TransformUtils.transform(param, ManageResource.class));
    }

    /**
     *根据id删除系统后台系统资源 递归删
     * @param ids 菜单id集合
     */
    public void deleteByIds(List<Long> ids){
        if(ObjectUtils.isEmpty(ids)){return;}
        List<ManageResource> allResourceList=manageResourceBusiness.findAll();
        List<ManageResourceResult> resourceResultList = TransformUtils.transformList(allResourceList, ManageResourceResult.class);
        Set<Long> allIds = new HashSet<>();
        ids.forEach(id->{
            ManageResourceResult root = ManageResourceResult.builder().id(id).build();
            getChildrenIds(root,resourceResultList,allIds);
        });
        allIds.addAll(ids);
        String deleteIds = StringUtils.join(allIds, ",");
        manageResourceBusiness.deleteByIds(deleteIds);
    }
    public Set<Long> getChildrenIds(ManageResourceResult root, List<ManageResourceResult> resourceResultList, Set<Long> childrenIds) {
        if(ObjectUtils.isEmpty(resourceResultList))return childrenIds;
         resourceResultList
                .stream()
                .filter(resource -> resource.getParentId().equals(root.getId()))
                .map(resource->{
                    childrenIds.add(resource.getId());
                    getChildrenIds(resource, resourceResultList,childrenIds);
                    return resource;
                })
                .collect(Collectors.toList());
        return childrenIds;
    }

    public static void main(String[] args) {
        List<Long> list = new ArrayList<>();
        list.add(1L);
        list.add(2L);
        list.add(3L);
        List<Long> collect = list.stream().map(i -> i + 1).collect(Collectors.toList());
        System.out.println(collect);
        System.out.println(collect);
    }

    public List<ResourceGroupTreeResult> queryAllResourceTree(Long roleId ){
        //List<ManageResource> allResourceList;
        List<ManageResourceResult> resourceTreeResults;
//        if(ObjectUtils.isEmpty(param)){
//            // 查询出所有的实体集合
//            allResourceList = manageResourceBusiness.findAll();
//            // 转换成结果集合
//            resourceTreeResults = TransformUtils.transformList(allResourceList, ManageResourceResult.class);
//
//        }else {
            // 这里查询用户所拥有的资源 用checked =1 标识拥有 方便前端处理
            // 转换成结果集合
            resourceTreeResults = TransformUtils.transformList(manageResourceBusiness.findResourceByRoleId(roleId), ManageResourceResult.class);
        //}
        Map<Long, List<ManageResourceResult>> maps = resourceTreeResults.stream().collect(Collectors.groupingBy(ManageResourceResult::getGroupId, Collectors.toList()));
        List<ResourceGroupTreeResult> resultList = new ArrayList<>();

        maps.forEach((key,value)->{
            List<ManageResourceResult> resourceResultList = toTree(value);
            resultList.add(ResourceGroupTreeResult.builder().groupId(resourceResultList.get(0).getGroupId()).groupName(resourceResultList.get(0).getGroupName()).groupStatus(resourceResultList.get(0).getGroupStatus()).resourceList(resourceResultList).build());

        });
        return resultList;

        // toTree
        //return toTree(resourceTreeResults);
    }

    public List<ManageResourceResult> toTree(List<ManageResourceResult> resourceResultList) {
        if(CollectionUtils.isEmpty(resourceResultList))return resourceResultList;
        return resourceResultList
                .stream()
                .filter(resourceTreeResult -> resourceTreeResult.getParentId() == 0)
                .map(resourceTreeResult -> {
                    resourceTreeResult.setChildren(getChildren(resourceTreeResult, resourceResultList));
                    return resourceTreeResult;
                })
                //.sorted(Comparator.comparing(ManageResourceResult::getSort))
                .collect(Collectors.toList());
    }

    public List<ManageResourceResult> getChildren(ManageResourceResult root, List<ManageResourceResult> resourceResultList) {
        if(CollectionUtils.isEmpty(resourceResultList))return resourceResultList;
        List<ManageResourceResult> collect = resourceResultList
                .stream()
                .filter(category -> category.getParentId().equals(root.getId()))
                .map(category->{
                    List<ManageResourceResult> children = getChildren(category, resourceResultList);
                    category.setChildren(children);
                    return category;
                })
                //.sorted(Comparator.comparing(ManageResourceResult::getSort))
                .collect(Collectors.toList());
        // 表示没子节点了
        if(CollectionUtils.isEmpty(collect)){
           // root.setName(root.getName()+"["+root.getId()+"]");
            // 结束递归
            return new ArrayList<>();
        }
        return collect;
    }

}
